package com.ys.basebindinggdemo.ui.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.ActionBar.LayoutParams
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import java.lang.reflect.ParameterizedType

abstract class BaseDialogFragment<VB : ViewDataBinding, VM : BaseViewModel> : DialogFragment() {

    lateinit var mBinding: VB
    lateinit var mViewModel: VM

    abstract fun init()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {


        val para = javaClass.genericSuperclass as ParameterizedType
        val type = para.actualTypeArguments[0] as Class<VB>
        val classMethod = type.getMethod("inflate", LayoutInflater::class.java)

        mBinding = classMethod.invoke(null, layoutInflater) as VB

        mBinding.lifecycleOwner = this

        val typeVM = para.actualTypeArguments[1] as Class<VM>
        mViewModel = ViewModelProvider(this)[typeVM]





        return mBinding.root
    }

    override fun onStart() {
        super.onStart()
        dialog?.window?.let {
            it.setLayout(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT)
            it.setBackgroundDrawableResource(android.R.color.transparent)

        }

        dialog?.setCanceledOnTouchOutside(false)
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        init()
    }


}